/*
 * Copyright 2008 Jens Meiss
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.hmvc4gwt.hmvc.gwt.framework.client.module;

import java.util.Map;

import com.googlecode.hmvc4gwt.hmvc.core.event.IEvent;
import com.googlecode.hmvc4gwt.hmvc.core.event.IEventListener;
import com.googlecode.hmvc4gwt.hmvc.core.registry.artifact.events.in.StartArtifactEvent;
import com.googlecode.hmvc4gwt.hmvc.core.registry.component.ComponentRegistry;
import com.googlecode.hmvc4gwt.hmvc.core.registry.component.events.in.SetSessionRegistryEvent;
import com.googlecode.hmvc4gwt.hmvc.core.registry.event.events.in.AddEventRegistryListenerEvent;
import com.googlecode.hmvc4gwt.hmvc.gwt.client.controller.AControllerGwt;
import com.googlecode.hmvc4gwt.hmvc.gwt.client.module.IModuleController;
import com.googlecode.hmvc4gwt.hmvc.gwt.framework.client.registry.session.SessionRegistryGwt;

/**
 * 
 * 
 * @author jens.meiss
 */
public abstract class AModuleControllerRegistry extends AControllerGwt
		implements IModuleController {

	public static boolean sessionRegistryStarted = false;

	public final void handleEvent(IEvent event) {

		if (event.getClass() == StartArtifactEvent.class) {
			startArtifact(((StartArtifactEvent) event).getArtifactClassName());
		}

		handleEventImpl(event);

	}

	public final void init() {

		/*
		 * listen to StartArtifacEvent's
		 */
		fireEventUp(new AddEventRegistryListenerEvent(StartArtifactEvent.class,
				this));

		/*
		 * start the SessionRegistry
		 */
		if (!sessionRegistryStarted) {
			fireEventUp(new SetSessionRegistryEvent(SessionRegistryGwt
					.getInstance()));
			sessionRegistryStarted = true;
		}

		initImpl();
	}

	public final void onModuleLoad() {
		new ComponentRegistry(this);
	}

	public final void registerEventListener(
			Map<Class<? extends IEvent>, IEventListener> mapEventListener) {
		registerEventListenerImpl(mapEventListener);
	}

	protected abstract void startArtifact(String classOfArtifact);

	public final void terminate() {
		terminateImpl();
	}
}
